package uy.edu.fing.pgsegesb.authentication;

import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.apache.log4j.Logger;
import org.picketlink.identity.federation.core.exceptions.ProcessingException;
import org.picketlink.identity.federation.core.wstrust.SamlCredential;
import org.picketlink.identity.federation.core.wstrust.auth.TokenCallback;
import org.jboss.internal.soa.esb.services.security.EsbCallbackHandler;
import org.jboss.soa.esb.services.security.SecurityConfig;
import org.jboss.soa.esb.services.security.auth.AuthenticationRequest;


public class ManualTokenCallbackHandler	implements EsbCallbackHandler 
	{
	    private Logger log = Logger.getLogger(ManualTokenCallbackHandler.class);
	     
	    private AuthenticationRequest authRequest;
	     
	    public ManualTokenCallbackHandler()
	    {
	    }
	     
	    public ManualTokenCallbackHandler(final AuthenticationRequest authRequest)
	    {
	        this.authRequest = authRequest;
	    }
	     
	    public void handle(final Callback[] callbacks) throws IOException, UnsupportedCallbackException
	    {
	        for (Callback callback : callbacks)
	        {
	            if (callback instanceof TokenCallback)
	            {
	                final TokenCallback tokenCallback = (TokenCallback) callback;
	                for (Object object : authRequest.getCredentials())
	                {
	                    if (object instanceof SamlCredential)
	                    {
	                        try
	                        {
	                            tokenCallback.setToken(((SamlCredential)object).getAssertionAsElement());
	                        }
	                        catch (ProcessingException e)
	                        {
	                            log.error(e.getMessage(), e);
	                        }
	                    }
	                }
	            }
	        }
	    }
	 
	    public void setAuthenticationRequest(AuthenticationRequest authRequest)
	    {
	        this.authRequest = authRequest;
	        
	    }
	 
	    public void setSecurityConfig(SecurityConfig config)
	    {
	    }
}
